package com.leehom.arch.storage.handler;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 
 * @类名: BaseFileStorageHandler
 * @说明: 存储基类，文件流处理公共类
 *
 * @author   leehom
 * @Date	 2018年3月13日 下午2:33:16
 * 修改记录：
 *
 * @see
 */
public abstract class BaseFileStorageHandler {
	
	private static final Logger logger = LoggerFactory.getLogger(BaseFileStorageHandler.class);
	
	/** */
	public static final int DEFAUT_BATCH_SIZE = 1024;
	
	protected void copyStream(InputStream in, OutputStream out) throws IOException {
		this.copyStream(in, out, DEFAUT_BATCH_SIZE);
	}
	
	protected void copyStream(InputStream in, OutputStream out, int batchSize) throws IOException {
		// 
		byte[] bt = new byte[batchSize];
		int size = 0;
		while ((size = in.read(bt)) != -1) {
			out.write(bt, 0, size);
		}
		out.flush();
	}
	
	protected void closeStream(InputStream in, OutputStream out) throws IOException {
		if(in!=null)
			in.close();
		if(out!=null)
			out.close();
	}
	
	// 连接文件路径
	protected String contactPath(String left, String right) {
		String seq = left.endsWith("/") || left.endsWith("\\") ? "" : File.separator;
		return left + seq + right;
	}

	protected PathAndName untactPath(String fullPath) {
		// 获取最后分隔符，"/" or "\"
		int a = fullPath.lastIndexOf("/");
		int b = fullPath.lastIndexOf("\\");
		a = a >= b ? a : b;
		//
		PathAndName pn = new PathAndName();
		// 没有分隔，即只有name
		if (a==-1) {
			pn.setName(fullPath);
			pn.setPath("");
			return pn;
		}
		//
		pn.setPath(fullPath.substring(0, a+1));
		pn.setName(fullPath.substring(a+1));
		return pn;
	}
}